package com.javafactroy.kunlong.bip.icp.context.connpool.nettyclient;

import com.javafactroy.kunlong.bip.icp.common.config.BipPoolConfig;
import com.javafactroy.kunlong.bip.icp.common.consts.EAppType;
import com.javafactroy.kunlong.bip.icp.context.AppContext;
import com.javafactroy.kunlong.bip.icp.netty.client.framework.NettyClient;
import lombok.Data;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.javafactroy.kunlong.bip.icp.message.base.iface.IMessage;

@Component
@Data
public class NettyClientPool {

    @Autowired
    NettyClientPoolFactory factory;
    @Autowired
    BipPoolConfig poolConfig;

    static volatile GenericObjectPool<NettyClient> objectPool;

    public NettyClientPool() {

    }

    public void setIpPort(String ip, int port) {
        getFactory().getBipConfig().setIpPort(ip, port);

    }

    GenericObjectPool<NettyClient> getPool() {
        if (objectPool == null) {
            synchronized (NettyClientPool.class) {
                if (objectPool == null) {
                    objectPool = new GenericObjectPool<NettyClient>(factory, poolConfig);
                }
            }
        }
        return objectPool;
    }


    public void returnObject(NettyClient client) {

        getPool().returnObject(client);

    }

    public NettyClient borrowObject() throws Exception {

        NettyClient nettyClient = getPool().borrowObject();
        if (AppContext.appContext.getMapNettyClient().get(nettyClient.getUuid()) == null) {
            nettyClient.start(EAppType.dxp);
        }
        return nettyClient;
    }

    public IMessage send(IMessage message) throws Exception {
        NettyClient nettyClient = borrowObject();
        try {
            return nettyClient.send(message);
        } finally {
            returnObject(nettyClient);
        }
    }


    public IMessage sendSyncMsg(IMessage message) throws Exception {
        NettyClient nettyClient = borrowObject();
        try {
            return nettyClient.sendSyncMsg(message);
        } finally {
            returnObject(nettyClient);
        }
    }

    public IMessage sendSyncMsgRetry(IMessage message) throws Exception {

        try {
            return sendSyncMsg(message);
        } catch (Exception e) {
            e.printStackTrace();
            return sendSyncMsg(message);
        }
    }
}










